|
ContentsRelational sublanguageSCL contains a small logic programming language. A query asks for every way to make
a set of facts true. The facts come from relations: a few built-in ones, relations
defined by rules written with This is an advanced feature. Nothing here is needed for ordinary SCL programming. The CHR engine of 4.02 Constraint Handling Rules is a separate mechanism that shares some syntax with this one; Relational queries and CHR at the end of this page compares the two. ImportsThe code that the compiler generates for these constructs calls functions of library modules, and a module that uses the constructs must import those modules:
Without them, the compiler reports the construct where it is written and names the
modules that are missing, for example select needs the ArrayList module, for example
through import "StandardLibrary". or A relation defined in a block needs the MList and
MSet modules, ... Any import of a module will do, even
A script, and the SCL Console, import Queries
A Names that start with
The query is a block of literals, one per line, or several on one line separated by
Patterns are written as in
Query variables exist only in queries and rules. A Order of evaluationThe literals are not evaluated in the order in which they are written. The compiler plans the order itself, from estimates of how many solutions each literal has, given the variables that are known at that point. A guard can therefore come before the list it filters:
The order of the results follows the plan and is not specified. Here the compiler loops
over
Sort the result if the order matters. The plan must give every query variable a value. A guard never does: it only tests values
that other literals have computed. A
|
| Relation | Meaning |
|---|---|
Eq a b |
a equals b; the literal a = b is this relation |
Optional x m |
m is Just x |
Execute action |
can only be enforced, which runs the action |
Execute10 action |
as Execute, but in phase 10 of a transformation |
lookupAll :: [Maybe Integer] -> [Integer]
lookupAll l = select ?x where
?m <- l
Optional ?x ?m
// lookupAll [Just 1, Nothing, Just 3] == [1, 3]
pattern <- list is a built-in relation as well, without a name. In a query, Execute
and Execute10 cannot be solved (Failed to compile the query.).
In a do, let or where block, a statement of the form Name arguments :- query is a
rule that defines a relation local to the block, in the manner of Datalog:
reachable :: [(Integer, Integer)] -> Integer -> [Integer]
reachable edges start = do
Edge ?a ?b :- (?a, ?b) <- edges
Path ?a ?b :- Edge ?a ?b
Path ?a ?c :- Path ?a ?b; Edge ?b ?c
sort (select ?x where Path start ?x)
// reachable [(1, 2), (2, 3), (3, 1), (4, 5)] 1 == [1, 2, 3]
The head Name arguments holds for every solution of the body. Several rules for the
same name add up, and rules may use each other and themselves. The arguments of the head
are expressions over the variables of the body, and the body must give a value to every
query variable in the head. A head variable without one crashes the compiler with
Variable ?y (with type ...) is not given value anywhere. All the rules of a relation
must have the same number of arguments (Different rules have different relation
arity.), and a head that is not of the form Name arguments is Invalid rule head.
A rule with an empty body, written {}, is a fact:
do
Parent "Ann" "Bob" :- {}
Parent "Bob" "Cid" :- {}
Parent "Bob" "Dan" :- {}
Grandparent ?g ?c :- Parent ?g ?p; Parent ?p ?c
sort (select ?c where Grandparent "Ann" ?c)
// ["Cid", "Dan"]
and a head may compute its arguments:
do
Even 0 :- {}
Odd (?n + 1) :- Even ?n; ?n < 9
Even (?n + 1) :- Odd ?n; ?n < 9
sort (select ?n where Even ?n)
// [0, 2, 4, 6, 8]
Adjacent rule statements form a group. The relations of a group can be used in all of its rules and in the rest of the block after it, but not in the statements before it.
When the block is evaluated, the relations of a group are computed completely, bottom up, until no rule adds anything new. The facts are kept in a set, so a fact is never repeated, and a query sees them in no particular order:
do
R ?x :- ?x <- [1, 1, 2]
R ?x :- ?x <- [2, 3]
sort (select ?x where R ?x)
// [1, 2, 3]
Relations defined in a block add no effect to the function that defines them, so
reachable above is a pure function. They have no sections, unlike the module-level
relations below, and enforce cannot add facts to them.
A rule can negate a relation of its block if the negated relation does not depend on the rule's own relation. Recursion through a negation is rejected with Recursion must not contain negations or aggragates. (sic).
do
Edge ?a ?b :- (?a, ?b) <- [(1, 2), (2, 3), (3, 4)]
Node ?a :- Edge ?a _
Node ?b :- Edge _ ?b
HasSuccessor ?a :- Edge ?a _
Sink ?a :- Node ?a; <!> HasSuccessor ?a
select ?a where Sink ?a
// [4]
HasSuccessor is a helper relation of the kind recommended under Negation: writing
<!> Edge ?a _ in Sink would leave _ unsolved.
A known defect affects recursive rules. When the body matches a pattern that mixes a variable bound by the recursive literal with a new variable, the compiler crashes with Variable ?b_temp (with type ...) is not given value anywhere. Match the whole element with new variables and compare them in a guard instead:
Below ?c :- Below ?b; (?b, ?c) <- edges // crashes
Below ?c :- Below ?b; (?p, ?c) <- edges; ?p == ?b // works
The same applies to mapping rules.
At the top level of a module, :- defines a relation that other modules can import like a
value. Its body is divided into sections, and each section starts with an annotation
that says when the section is used:
Between ?lo ?hi ?x :-
@bbb 0.5
?lo <= ?x
?x <= ?hi
@bbf 10
?x <- [?lo .. ?hi]
main :: ([Integer], [Integer])
main = ((select ?x where Between 1 5 ?x; ?x > 3),
(select ?x where ?x <- [0, 3, 9]; Between 1 5 ?x))
// ([4, 5], [3])
The letters name a binding pattern, one letter for each argument: b means that the
argument is bound, that is, its value is known when the relation is used, and f that it
is free and the section must compute it. The number after the pattern is optional. It
estimates how many solutions the section has for one combination of bound values, and the
compiler uses it to plan queries. The default is 10, and a number below 1 suits a section
that only tests.
When a query uses the relation, the compiler takes the first section whose b
arguments are all known at that point. Above, Between 1 5 ?x alone uses @bbf, while in
?x <- [0, 3, 9]; Between 1 5 ?x the compiler computes ?x first and uses the cheaper
@bbb. Put the more specific sections first: a section that an earlier one covers would
never be used, and it is rejected with Query section is redundant because the previous
sections cover it. When no section fits, the query cannot be solved:
select ?lo where Between ?lo 5 3 is Unsolved variables: ?lo.
A section can have query variables of its own:
Neighbour ?a ?b :-
@bf 2
?d <- [-1, 1 :: Integer]
?b = ?a + ?d
// select ?b where Neighbour 5 ?b == [4, 6]
An @enforce section says what enforce does for the relation, see enforce.
Its optional number is the phase in which a transformation enforces the relation. A
relation may have an @enforce section and no query sections at all.
The current compiler restricts module-level relations in several ways:
?x <~ ?y, is A relation definition starts with the relation name followed by its
parameters, which are variables such as ?x., and an argument such as 1 is A
parameter of a relation must be a variable, such as ?x.@enforce as an integer. Otherwise the error is The selectivity of a query section must
be a number. or The phase of @enforce must be an integer.StackOverflowError. Define recursive relations in a block.Ring a cannot be part of them. A numeric
literal therefore needs a type annotation, as in Neighbour. Without it the error is
Constraint The Data/XML module defines its Element, Attribute and TextContent relations this
way, with query sections for several binding patterns and @enforce sections that change
the document.
enforceenforce makes the literals of a block true, one after another in the order in which
they are written, and returns ():
main = do
enforce
Execute (print "first")
Execute (print "second")
"done"
prints first and second. What making a literal true means depends on its relation:
| Literal | What enforce does |
|---|---|
Execute action, Execute10 action |
runs the action |
| a module-level relation | enforces the literals of its @enforce section |
Statement s p o of Minigraph |
adds the statement to the graph |
| a relation of an ontology module | claims the statement, or sets the property value |
For example,
Logged ?message :-
@enforce
Execute (print ("log: " + ?message))
main = do
enforce
Logged "starting"
Logged "stopping"
"done"
prints log: starting and log: stopping.
Every value must be known: a query variable in an enforce block is QExists does not
support enforcing. Other literals are not supported, and most of them crash the
compiler:
| Literal | Result |
|---|---|
pattern = expression |
UnsupportedOperationException: EqRelation does not support enforce. |
pattern <- list |
UnsupportedOperationException: MemberRelation does not support enforce. |
| a guard | UnsupportedOperationException: CheckRelation does not support enforce. |
| a relation defined in a block | UnsupportedOperationException: LocalRelation does not support enforce. |
a module-level relation without @enforce |
NullPointerException |
| a disjunction block | QDisjunction does not support enforcing. |
Phases do not matter to enforce itself: Execute10 runs in its place in the block like
any other literal. Phases only order the actions of a transformation.
Known defect: the type checker does not see the effects of what enforce runs, nor the
effects of the relations that a query reads. The function
shout s = enforce Execute (print s) can be declared String -> (), and a query over
graph relations does not require <ReadGraph>. Declare the effects yourself, and make
sure that code using graph relations runs in a transaction.
MinigraphThe built-in module Minigraph contains a tiny in-memory graph for testing. It is enough
to try queries and enforce on graph-shaped data without a database:
import "Minigraph"
main = withGraph do
inverseOf = resource "Layer0/InverseOf"
hasChild = resource "hasChild"
hasParent = resource "hasParent"
a = resource "a"
b = resource "b"
c = resource "c"
enforce
Statement hasChild inverseOf hasParent
Statement a hasChild b
Statement a hasChild c
(sort (map uriOf (select ?x where Statement a hasChild ?x)),
map uriOf (select ?p where Statement ?p hasChild c))
// (["b", "c"], ["a"])
withGraph runs an action with a new, empty graph. resource returns the resource with
the given URI and creates it if needed; resources are integers. uriOf returns the URI,
and Statement subject predicate object is the relation of the statements of the graph.
As in the Simantics database, a query must know the predicate, and subjects can only be
searched through an inverse relation, which is declared with Layer0/InverseOf.
In Simantics, an ontology module exports the relations of the ontology as SCL relations,
under the same names as their resources. With
import "http://www.simantics.org/Layer0-1.1" as L0, the query literal
L0.ConsistsOf ?parent ?child reads statements from the database, and enforcing it
claims a statement. A functional property relation with a known value type, such as
L0.HasName, relates a resource to the value of the property instead: a query reads the
value and enforce sets it. The subjects of a statement can be searched only if the
relation has an inverse, and a property relation cannot be searched by its value. Queries
need a read transaction and enforce a write transaction, which the compiler does not
check.
A mapping relation is a function from source values to target values that a transformation builds up while it runs. It is declared at module level with its source and target types:
mapping relation PathOf String String
A mapping rule is a module-level declaration whose body is divided into sections. A
transformation matches the literals of the rule's @when and @from sections, and for
every match it enforces the literals of its @to and @where sections. A
transformation expression runs the mapping rules of its module, starting from the
mapping facts listed after where, its seeds:
childrenOf :: String -> [String]
childrenOf "root" = ["a", "b"]
childrenOf "a" = ["c"]
childrenOf _ = []
mapping relation PathOf String String
rule Children where
@when
PathOf ?node ?path
@from
?child <- childrenOf ?node
@where
PathOf ?child (?path + "/" + ?child)
rule Report where
@when
PathOf ?node ?path
@to
Execute (print "\(?node) is at \(?path)")
main = transformation OneShotForward where
PathOf "root" "/root"
prints
b is at /root/b
c is at /root/a/c
root is at /root
a is at /root/a
and returns (). A transformation runs in two steps:
"root" to "/root". A mapping
literal in a matched section, such as PathOf ?node ?path, matches every source that
has been mapped. A mapping literal in an enforced section maps a new source, here each
child of a matched node, and the new source can be matched in turn, by any rule. This
repeats until nothing new is mapped.enforce, once for every match of their rule. First come the literals of phase 0 of
all the rules, rule by rule, then those of phase 10 (Execute10, and module-level
relations whose @enforce section has phase 10), and so on. The rules of one module
come in source order. The transformation expression below orders the rules of
several modules.The order in which the matches of a rule are enforced is not specified. As the output above shows, it need not be the order in which the sources were mapped.
The target of a mapping literal in a matched section, ?path above, can only be used in
the enforced sections. A guard such as ?path != "/root" in @when cannot be solved
(Unsolved variables: ?path).
@when.@where, a literal Name a b whose name is not a declared mapping relation declares
one implicitly, with types inferred from its use, even if a relation of that name
exists. Put all other literals in @to. Execute in a @where section, for instance,
becomes a mapping relation and fails with An arity of mapping relation should always be
2.RuntimeUnificationException. The values are unified rather than compared,
so two rules can each give a part of a structured value, such as (1, ?x) and
(?y, 2), which together make (1, 2).Resource, "" for String, a new element for the Element type of
Data/XML, and a tuple of default values for a tuple type. Any other type fails at run
time with Cannot generated default instance for type ... (sic).The sections that a mapping rule can have are
| Section | What a transformation does with it |
|---|---|
@when |
matches it |
@from |
matches it |
@to |
enforces it |
@where |
enforces it; also declares mapping relations implicitly |
@fromCondition |
matches it |
@fromEnforce, @fromDefault |
enforces it |
@toCondition, @toEnforce, @toDefault |
ignores it |
Any other name is Invalid section name foo. The names come from a design for
transformations in both directions, in which @from and @to describe the source and
target patterns, @when and @where the mappings that a rule needs and creates, and a
backward transformation would match @to and enforce @from. Only the forward
transformation is implemented, so apart from the implicit declarations in @where,
@when works like @from and @where like @to.
An abstract rule is not run by a transformation itself. Other rules include its sections
with extends:
mapping relation M Integer Integer
abstract rule Positive where
@when
M ?a ?b
?a > 0
rule Report extends Positive where
@to
Execute (print "\(?a) -> \(?b)")
main = transformation OneShotForward where
M 1 10
M 0 20
prints 1 -> 10 only. A rule can extend several rules, rule R extends A, B where, and
its sections and those of the rules it extends share variables by name. Each variable may
come from only one of the extended rules (Variable ?a is defined in more than one base
rule, which is not currently allowed.). An unknown name is Couldn't resolve rule name
A., and a cycle of extends crashes the compiler with a StackOverflowError.
transformation expression(), and it has the <Proc> effect.transformation is only a label. Every transformation is a one-shot
forward transformation, and the examples name it OneShotForward.import "M" () brings in the rules of M too.The CHR engine of 4.02 Constraint Handling Rules also has rules, ?x variables and
select, but it is a different mechanism:
| Relational sublanguage | CHR | |
|---|---|---|
| Facts live in | relations: lists, rules, graphs | a constraint store |
| Rules | Head :- body derives facts; mapping rules |
head => body or when head then body |
| Evaluation | a query searches; block relations are computed to a fixed point | forward chaining, which can remove facts |
| Negation | <!>, stratified |
not supported |
| Writing facts | enforce, transformations |
rule bodies add constraints |
| In a script | queries, enforce, block relations and transformations work |
does not work |
The two meet in a module whose header enables the chr feature. There a plain select is
a CHR query. It cannot use the relations of this page, and on a relation defined in a
block it crashes with LocalRelation does not support iterate. select first and
select distinct remain relational queries, and :- relations and enforce keep
working, but rule and transformation are ordinary identifiers, so a chr module
cannot have mapping rules.
A script imports StandardLibrary, so queries need no imports:
> select ?x where ?x <- [1, 2, 3]; ?x > 1
[2, 3]
> select first ?x where ?x <- [1, 2, 3]; ?x > 1
Just 2
> enforce Execute (print "enforced")
enforced
A relation can be defined in a do block and used in the same block:
> do
Small ?x :- ?x <- [1, 2, 3]
select ?x where Small ?x; ?x > 1
[3, 2]
At the top level of a script, a relation definition is accepted, but each statement is compiled on its own, so the next statement cannot see the relation:
> Small ?x :- ?x <- [1, 2, 3]
> select ?x where Small ?x
Couldn't resolve Small.
Module-level relations with sections, mapping relation and rule are syntax errors in a
script. Put them in a module and import the module into the script. A transformation
written in the script runs the rules of the modules that the script imports. If a module
Paths contains childrenOf, PathOf and the two rules of Mapping rules and
transformations,
> import "Paths"
> transformation OneShotForward where
PathOf "root" "/root"
b is at /root/b
c is at /root/a/c
root is at /root
a is at /root/a
See also 1.18 Modules vs. scripts.
| Message | Cause |
|---|---|
| select needs the ArrayList module, for example through import "StandardLibrary". | a select in a module that does not import ArrayList, see Imports |
| tc needs the MSet module, ... | a tc in a module that does not import MSet, see Imports |
| A relation defined in a block needs the MList and MSet modules, ... | relations defined in a block in a module that imports neither, see Imports |
| transformation needs the MList, MSet and Unification modules, ... | a transformation in a module that imports none of them, see Imports |
| Failed to compile the query. | no evaluation order gives every variable a value; Unsolved variables lists them |
| New existential variables can be defined only in queries. | ?x outside a query |
| Blank variables can be used only in queries. | _ in an expression outside a query |
| Select expression produces a list of values. | select where another type is expected |
| Select first expression produces an optional value. | select first where another type is expected |
| Relation is applied with wrong number of parameters. | a query literal with too many or too few arguments |
| Different rules have different relation arity. | the rules of a block relation disagree |
| Invalid rule head. | a block rule whose head is not Name arguments |
| Recursion must not contain negations or aggragates. | recursion through <!> |
| A relation definition starts with the relation name followed by its parameters, ... | a module-level relation without arguments, or with an operator head |
| A parameter of a relation must be a variable, such as ?x. | a head argument of a module-level relation that is not a variable |
| The relation has no section annotation before its first query. ... | a module-level relation body that does not start with a section annotation |
| Invalid section name 'q'. | an unknown section in a module-level relation |
| The selectivity of a query section must be a number. | a binding pattern followed by something other than a number |
| The phase of @enforce must be an integer. | @enforce followed by something other than an integer |
| Query section is redundant because the previous sections cover it. | sections in the wrong order |
| Does not yet support definition of relations by more than one rule. | a module-level relation defined twice |
| Constraint |
a module-level relation that needs a type annotation |
| QExists does not support enforcing. | a query variable in enforce |
| QDisjunction does not support enforcing. | a <|> block in enforce |
| Mapping relation M has already been defined. | two declarations of one mapping relation |
| Rule R has already been defined. | two rules with one name |
| Invalid section name foo. | an unknown section in a mapping rule |
| Couldn't resolve rule name A. | extends names no rule |
| Variable ?a is defined in more than one base rule, ... | two extended rules share a variable |
| An arity of mapping relation should always be 2. | usually a literal that is not a mapping in @where |
| Cannot use the query as a seed for the transformation. | a seed that is not a mapping literal |
| Cannot resolve the variable ?b using the source patterns. | the source of a mapping in an enforced section is not matched |
| Cannot generated default instance for type ... | at run time: no default value for an unbound target variable |
The following are defects of the current compiler rather than design decisions. Each is described in its section above.
<?> crashes the compiler.<!>, a block relation with unknown arguments crashes the compiler, and a pattern
that mixes an exists variable with an outer one produces a module that fails to load.tc prints debugging output, and crashes the compiler if neither end is known.enforce does not support crash the compiler instead of being
reported as errors.enforce and of the relations that a query reads are not checked.extends crashes the compiler.<|> that leaves a
variable without a value, crash the compiler instead of being reported as errors.The compiler's regression fixtures contain working queries, relations and transformations:
tests/org.simantics.scl.compiler.tests/src/org/simantics/scl/compiler/tests/scl/Select*.scl
tests/org.simantics.scl.compiler.tests/src/org/simantics/scl/compiler/tests/scl/Relations*.scl
tests/org.simantics.scl.compiler.tests/src/org/simantics/scl/compiler/tests/scl/Transformation*.scl
Each file contains the module text, a -- separator and the expected output. In the
bundle org.simantics.scl.data, the Data/XML module defines module-level relations over
XML documents, and the examples folder has transformations from one XML document to
another.